'use client'

import React, { ReactNode, useRef, useState } from 'react'
import { Box, useColorModeValue } from '@chakra-ui/react'
import { DragItem, DragData } from '@/types/drag-drop'

interface DraggableItemProps {
  item: DragItem;
  children: ReactNode;
  onDragStart?: (item: DragItem) => void;
  onDragEnd?: (item: DragItem, dropped: boolean) => void;
  className?: string;
  disabled?: boolean;
}

export const DraggableItem: React.FC<DraggableItemProps> = ({
  item,
  children,
  onDragStart,
  onDragEnd,
  className = '',
  disabled = false
}) => {
  const [isDragging, setIsDragging] = useState(false)
  const dragRef = useRef<HTMLDivElement>(null)
  const sourceId = `draggable-${item.id}`
  
  const bgColor = useColorModeValue('white', 'gray.800')
  const hoverBgColor = useColorModeValue('gray.50', 'gray.700')
  const draggingBgColor = useColorModeValue('gray.100', 'gray.600')
  const borderColor = useColorModeValue('gray.200', 'gray.600')
  
  const handleDragStart = (e: React.DragEvent<HTMLDivElement>) => {
    if (disabled) return
    
    setIsDragging(true)
    
    // 设置拖拽图像（可选）
    if (dragRef.current) {
      // 创建一个半透明的拖拽图像
      const rect = dragRef.current.getBoundingClientRect()
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      if (ctx) {
        canvas.width = rect.width
        canvas.height = rect.height
        ctx.fillStyle = 'rgba(200, 200, 200, 0.5)'
        ctx.fillRect(0, 0, canvas.width, canvas.height)
        ctx.font = '14px Arial'
        ctx.fillStyle = 'black'
        ctx.fillText(item.name, 10, 25)
        e.dataTransfer.setDragImage(canvas, 10, 10)
      }
    }
    
    // 设置拖拽数据
    const dragData: DragData = {
      items: [item],
      sourceId,
      timestamp: Date.now()
    }
    
    e.dataTransfer.setData('application/json', JSON.stringify(dragData))
    e.dataTransfer.effectAllowed = 'copy'
    
    // 触发回调
    if (onDragStart) {
      onDragStart(item)
    }
  }
  
  const handleDragEnd = (e: React.DragEvent<HTMLDivElement>) => {
    setIsDragging(false)
    
    // 触发回调
    if (onDragEnd) {
      const dropped = e.dataTransfer.dropEffect !== 'none'
      onDragEnd(item, dropped)
    }
  }
  
  return (
    <Box
      ref={dragRef}
      draggable={!disabled}
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
      className={`draggable-item ${className} ${isDragging ? 'dragging' : ''}`}
      data-item-id={item.id}
      data-item-type={item.type}
      cursor={disabled ? 'default' : 'grab'}
      bg={isDragging ? draggingBgColor : bgColor}
      _hover={{ bg: disabled ? undefined : hoverBgColor }}
      borderWidth={1}
      borderColor={isDragging ? 'blue.400' : borderColor}
      borderStyle="solid"
      borderRadius="md"
      transition="all 0.2s"
      opacity={isDragging ? 0.7 : 1}
      boxShadow={isDragging ? 'md' : 'none'}
      position="relative"
      userSelect="none"
    >
      {children}
    </Box>
  )
}
